package com.fjwt.gz.coupon.yspay.yspayutil;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.fjwt.gz.coupon.yspay.YspayIsvParams;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.FileInputStream;
import java.io.InputStream;
import java.security.PublicKey;
import java.security.Signature;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class YsPayUtil {




    /**
     * 异步通知参数验签
     */
    public static boolean asynVerifyYs(Map<String, String> reqMap, YspayIsvParams isvParams,com.alibaba.fastjson2.JSONObject authConfig) throws Exception {
        log.info("银盛验签，reqMap:{},isvParams:{}",JSONUtil.toJsonStr(reqMap),JSONUtil.toJsonStr(isvParams));
        boolean flag = false;
        //请用银盛的公钥证书
        PublicKey ysPayPublicKey = getYsPayPublicKey(isvParams,authConfig);

        String sign = reqMap.get("sign");
        String content = StringUtil.createLinkString(CommonUtil.paraFilter(reqMap));
        Signature signetcheck = Signature.getInstance("SHA1WithRSA");
        signetcheck.initVerify(ysPayPublicKey);
        signetcheck.update(content.getBytes("UTF-8"));
        if (signetcheck.verify(Base64.getDecoder().decode(sign.getBytes("UTF-8")))) {
            flag = true;
        }

        return flag;
    }

    /**
     * 发送http请求获取返回结果，请求地址以文档为准
     *
     * @param isvParams
     * @param reqMap
     * @return
     * @throws Exception
     */
    public static Map<String, String> http(YspayIsvParams isvParams, Map<String, String> reqMap, String HTTP_URL,String repMethod, com.alibaba.fastjson2.JSONObject authConfig) throws Exception {

        Map<String, String> resMap = new HashMap<>();
        log.info("发起银盛请求:{}", JSONUtil.toJsonStr(reqMap));
        String result = HttpRequest.sendPost(HTTP_URL, CommonUtil.mapToString(reqMap));
        log.info("同步返回结果:{}", result);


        if (StrUtil.isBlank(result)) {
            log.error("同步返回结果为空");
        }

        boolean resultVerify = false;
        try {
            //执行验签， repMethod 各个接口的值均不同，可以从返回结果中查看
            resultVerify = resultVerify(isvParams,result, repMethod,authConfig);
            log.info("同步请求验签结果:{}", resultVerify);
        } catch (Exception e) {
            log.error("同步请求验签异常");
        }
        resMap = JSONUtil.toBean(result,Map.class);
        return resMap;
    }

    /**
     * 同步返回参数验签
     *
     * @throws Exception
     */
    public static boolean resultVerify(YspayIsvParams isvParams, String resTest, String repMethod, com.alibaba.fastjson2.JSONObject authConfig) throws Exception {

        boolean flag = false;
        JSONObject jsonObject = JSON.parseObject(resTest, Feature.OrderedField);
        log.debug("jsonObject:" + jsonObject);
        String content = jsonObject.get(repMethod).toString();
        String sign = jsonObject.get("sign").toString();
        log.debug("sign:" + sign + "content:" + content);
        //请用银盛的公钥证书
        PublicKey ysPayPublicKey = getYsPayPublicKey(isvParams,authConfig);

        Signature signetcheck = Signature.getInstance("SHA1WithRSA");
        signetcheck.initVerify(ysPayPublicKey);
        signetcheck.update(content.getBytes("UTF-8"));
        if (signetcheck.verify(Base64.getDecoder().decode(sign.getBytes("UTF-8")))) {
            flag = true;
        }

        return flag;
    }

    /**
     * 请用银盛的公钥证书
     *
     * @return
     * @throws Exception
     */
    private static PublicKey getYsPayPublicKey(YspayIsvParams isvParams, com.alibaba.fastjson2.JSONObject authConfig) throws Exception {
        InputStream publicCertFileInputStream =  new FileInputStream(authConfig.getString("certFilePath"));
        PublicKey publicKey = YsPaySignUtils.getPublicKeyFromCert(publicCertFileInputStream);
        if (publicCertFileInputStream != null) {
            publicCertFileInputStream.close();
        }

        return publicKey;
    }


}
